package com.tbit.main.pojo.maintain_performance.rule;

import com.tbit.main.pojo.maintain_performance.Range;
import com.tbit.main.pojo.maintain_performance.constant.RuleTypeConstant;
import lombok.Data;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * @description: 基于时间段和时效的规则
 * @author: qiu.longjie
 * @create: 2025-04-07
 */
@Data
public class IntervalAndValidityBasedRule {

    /**
     * 任务完成时间范围
     */
    private Range<String> completedDuration;

    /**
     * 规则类型
     */
    private String ruleType;

    /**
     * 时段或时效对应绩效配置
     */
    private List<IntervalAndValidityBasedSubRule> subRules;

    /**
     * 根据时间段计算绩效
     */
    public IntervalAndValidityBasedSubRule calculatePerformance(LocalDateTime changeTime, LocalDateTime orderTime) {
        // 不是基于时间间隔的规则不处理
        if (!RuleTypeConstant.INTERVAL_BASED_RULE.equals(ruleType)) {
            return null;
        }
        if (subRules != null && !subRules.isEmpty()) {
            LocalDate changeDate = changeTime.toLocalDate();
            for (IntervalAndValidityBasedSubRule subRule : subRules) {
                LocalTime start = LocalTime.parse(subRule.getOrderIntervalOrHour().getStart2Calc());
                LocalTime end = LocalTime.parse(subRule.getOrderIntervalOrHour().getEnd2Calc());

                LocalDateTime startDateTime;
                LocalDateTime endDateTime;

                if (start.isBefore(end)) {
                    // 不跨天
                    startDateTime = LocalDateTime.of(changeDate, start);
                    endDateTime = LocalDateTime.of(changeDate, end);
                } else {
                    // 跨天
                    startDateTime = LocalDateTime.of(changeDate, start);
                    changeDate = changeDate.plusDays(1);// 跨天就加1,下一个时间段就是跨天后的日期的时间段，所以这里要加1天
                    endDateTime = LocalDateTime.of(changeDate, end);
                }
                // 判断订单时间是否在时间段内
                if (orderTime.isAfter(startDateTime) && orderTime.isBefore(endDateTime)) {
                    return subRule;
                }
            }
        }
        return null;
    }

    /**
     * 根据时效计算绩效
     *
     * @param hours 时间时长（小时）
     * @return
     */
    public IntervalAndValidityBasedSubRule calculatePerformance(int hours) {
        // 不是基于时效的规则不处理
        if (!RuleTypeConstant.VALIDITY_BASED_RULE.equals(ruleType)) {
            return null;
        }
        if (subRules != null && !subRules.isEmpty()) {
            for (IntervalAndValidityBasedSubRule subRule : subRules) {
                Range range = new Range<Integer>();
                range.setStart(Integer.parseInt(subRule.getOrderIntervalOrHour().getStart2Calc()));
                range.setEnd(Integer.parseInt(subRule.getOrderIntervalOrHour().getEnd2Calc()));
                if (range.match(hours)) {
                    return subRule;
                }
            }
        }
        return null;
    }
}
